package com.jh.complicate.netty.buffer;

import java.nio.Buffer;
import java.nio.ByteBuffer;

/**
 * @author Administrator
 * @projectName newforward
 * @title ReadOnlyBuffer.java
 * @package com.jh.complicate.netty.buffer
 * @description 只读缓冲区
 * @date 2019/6/23 21:52
 */
public class ReadOnlyBuffer {
    public static void main(String[] args){
        // 初始化buffer
        ByteBuffer buffer = ByteBuffer.allocate(10);

        // put值到buffer中
        for (int i = 0; i < buffer.capacity(); i++) {
            buffer.put((byte) i);
        }

        // 将buffer的position重置为0，且将limit设置为put的最后位置
        buffer.flip();

        // 生成readOnly buffer
        ByteBuffer readOnly = buffer.asReadOnlyBuffer();

        // 拿出里面的值
        System.out.println("before change read：");
        while (readOnly.hasRemaining()) {
            System.out.print(readOnly.get() + " ");
        }
        System.out.println("");

        // 修改原来的buffer的值
        for (int i = 0; i < buffer.capacity(); i++) {
            byte b = buffer.get(i);
            b *= 10;
            buffer.put(i, b);
        }

        // 重置位置
        readOnly.position(0);
        readOnly.limit(readOnly.capacity());

        // 重新输出，校验数据是否发生变化
        System.out.println("after change read：");
        while (readOnly.hasRemaining()) {
            System.out.print(readOnly.get() + " ");
        }
        System.out.println("");

    }
}
